<?php

namespace App\Http\Controllers\Alipay;

use App\Enums\GoodsBusinessEnum;
use App\Enums\SmsTempEnum;
use App\Jobs\ProcessPodcast;
use App\Jobs\SendChangeOrderMessage;
use App\Jobs\SendSmsMessageJob;
use App\Models\AuthenticLog;
use App\Models\Goods;
use App\Models\GoodsRentSku;
use App\Models\GoodsRentSkuMeal;
use App\Models\MemberOther;
use App\Models\OrderDlzwRisk;
use App\Models\OrderGoods;
use App\Models\OrderLease;
use App\Models\TwoElements;
use App\Services\AlipayMessageService;
use App\Services\AlipayMiniAppService;
use App\Models\Order;
use App\Services\CommonService;
use App\Services\EducationService;
use App\Services\GoodsService;
use App\Services\IdCardService;
use App\Services\OrderService;
use App\Services\RelationVerifyService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;


class OrderNewController extends BaseController
{

    public function idCardImg(Request $request)
    {
        $user = $this->member;
        $order_id = $request->input('order_id');
        $model = Order::where('uid', $user['id']);
        $model = $model->where('id', $order_id);
        $info = $model->first();
        if (!$info) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '订单不存在', 'data' => []];
        }

        $contact_name = $request->input('contact_name');
        $contact_mobile = $request->input('contact_mobile');
        $contact_type = $request->input('contact_type');

        $contact_name_two = $request->input('contact_name_two');
        $contact_mobile_two = $request->input('contact_mobile_two');
        $contact_type_two = $request->input('contact_type_two');
        $card_back = $request->input('card_back');
        $card_front = $request->input('card_front');
        if (!$card_front || !$card_back) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请上传身份证正面和反面');
        }

        if (!$contact_name) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '请输入紧急联系人姓名', 'data' => []];
        }
        if (!$contact_mobile) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '请输入紧急联系人手机号', 'data' => []];
        }
        if (!$contact_type) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '请选择关系', 'data' => []];
        }

        if (!$contact_name_two) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '请输入紧急联系人2姓名', 'data' => []];
        }
        if (!$contact_mobile_two) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '请输入紧急联系人2手机号', 'data' => []];
        }
        if (!$contact_type_two) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '紧急联系人2关系不能与紧急联系人1关系一致', 'data' => []];
        }


        if($contact_mobile_two==$contact_mobile){
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '紧急联系人2手机号不能与紧急联系人1一致', 'data' => []];
        }
        if($contact_name_two==$contact_name){
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '紧急联系人2姓名不能与紧急联系人1一致', 'data' => []];
        }

        if($contact_type_two==$contact_type){
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '紧急联系人2姓名不能与紧急联系人1一致', 'data' => []];
        }



        if (empty($contact_name) || empty($contact_mobile)) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '该订单必须填写紧急联系人信息，如页面无输入框，请下拉刷新页面！', 'data' => []];
        }
        if (trim($user['cert_name']) == trim($contact_name) || trim($user['mobile']) == trim($contact_mobile)) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '紧急联系人信息不能与收货人信息一致', 'data' => []];
        }
        if (trim($user['cert_name']) == trim($contact_name_two) || trim($user['mobile']) == trim($contact_mobile_two)) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '紧急联系人信息不能与收货人信息一致', 'data' => []];
        }


        if (!Verify_Phone($contact_mobile)) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '手机号码有误');
        }

        $res = EducationService::queryTwoName( ['phone' => $contact_mobile, 'name' =>$contact_name]);
        $res = json_decode($res, true);
        if ($res['code'] == '0' && $res['data']['VerificationResult'] != '-1') {
               $data = ['order_id' => $order_id, 'relate' =>$contact_type, 'phone' => $contact_mobile, 'name' =>$contact_name];
               $data['result'] = $res['data']['ISP'];
                TwoElements::query()->insert($data);
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '查询失败，紧急联系人1 号码与姓名验证错误');
        }

        $res = EducationService::queryTwoName( ['phone' => $contact_mobile_two, 'name' =>$contact_name_two]);
        $res = json_decode($res, true);
        if ($res['code'] == '0' && $res['data']['VerificationResult'] != '-1') {
            $data = ['order_id' => $order_id, 'relate' =>$contact_type_two, 'phone' => $contact_mobile_two, 'name' =>$contact_name_two];
            $data['result'] = $res['data']['ISP'];
            TwoElements::query()->insert($data);
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '查询失败，紧急联系人2 号码与姓名验证错误');
        }

        if (!$user['cert_no'] || !$user['cert_name']) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '未实名认证', 'data' => []];
        }

        if ($user['idcard_front'] && $user['idcard_back']) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '已经上传过身份证', 'data' => []];
        }

        $authenticLog = AuthenticLog::where(['cert_no' => $user['cert_no'],  'uid' => $user['id'],'status'=>1])->orderBy('id', 'desc')->first();
        if (!$authenticLog) {
            return ["status" => CommonService::HTTP_CODE_FAIL, "msg" => '实名记录不存在'];
        }
        $res = IdCardService::build(['infoImg' => imgToBase64(config('alipay.oss.imgHost') . $card_front), 'emblemImg' => imgToBase64(config('alipay.oss.imgHost') . $card_back)]);
        if ($res['curlRes']['code'] != 0) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, $res['curlRes']['message']);
        }
        if ($res['curlRes']['data']['name'] != $authenticLog->cert_name) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '填写的姓名与身份证不一致');
        }
        if ($res['curlRes']['data']['idNo'] != $authenticLog->cert_no) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '填写的身份证号与身份证不一致');
        }
        if ($res['curlRes']['data']['validityPeriod']) {
            $validityPeriod = explode('-', $res['curlRes']['data']['validityPeriod']);
            $dateString = $validityPeriod[1];
            $dateArray = explode('.', $dateString); // 将日期分割为数组
            $correctDateString = implode('-', $dateArray); // 将数组元素用 - 连接，得到正确的日期格式
            $timestamp = strtotime($correctDateString); // 转换为时间戳
            if ($timestamp < time()) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '身份证有效期已过期,请重新提交');
            }
        }
        if($res['curlRes']['data']['address']){
            if(!empty($res['curlRes']['data']['address'])&&in_array(mb_substr($res['curlRes']['data']['address'],0,2),['内蒙','西藏','新疆'])){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '校验不通过');
            }
        }



        // ===================事务开始
        DB::beginTransaction();
        try {
            Order::where('id', $order_id)->update([
                'emergency_contact' => $contact_type . ":" . $contact_name . ":" . $contact_mobile
            ]);


            $data = [
                'idcard_front' => $card_front,
                'idcard_back' => $card_back,
            ];
            AuthenticLog::where(['id' => $authenticLog['id']])->update($data);
            MemberOther::query()->where('id', $user['id'])->update(['idcard_front' => $card_front,
                'idcard_back' => $card_back]);
        } catch (\Exception $e) {
            DB::rollBack();
            return ["status" => CommonService::HTTP_CODE_FAIL, "msg" => '下单失败' . $e->getMessage()];
        }
        DB::commit();
        return ['status' => CommonService::HTTP_CODE_SUCCESS, 'msg' => '上传成功', 'data' => []];
    }

    public function orderInfo(Request $request)
    {
        ///$data = $request->input();
        //$miniId = AlipayMiniAppService::getInstance()->getMiniId();
        $user = $this->member;

        $order_id = $request->input('order_id');
        $trade_no = $request->input('trade_no');
        if (!$order_id && !$trade_no) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数错误');
        }
        // return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', ["user"=>$user['id']]);

        $model = Order::where('uid', $user['id']);

        if (!empty($order_id)) {
            $model = $model->where('id', $order_id);
        }
        if (!empty($trade_no)) {
            $model = $model->where('trade_no', $trade_no);
        }

        $order = $model->with('order_goods')
            ->with('authentic_log')
            ->with(['shop' => function ($query) {
                $query->select("id", "member_id", "shopname");
            }])
            ->first();
        if (empty($order)) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }
        $order->order_goods['num'] = 1;
        $order->begin_time = date('Y.m.d', strtotime($order->begin_time));
        $order->end_time = date('Y.m.d', strtotime($order->end_time));

        $order['b_e_time'] = $order->begin_time . ' - ' . $order->end_time;


        $order_lease = OrderLease::where('order_id', $order->id)
            ->orderBy('which_period', 'asc')
            ->get();


        // $order['month_total'];
        $order['first_num'] = 1;
        $order['first_rent'] = $order_lease[0]['rent'];
        $order['last_num'] = 0;


        $order['last_rent'] = $order_lease[count($order_lease) - 1]['rent'];

        if ($order['month_total'] > 1) {
            $second_rent = $order_lease[1]['rent'];
            //$order['ssss']= $order_lease['last_rent'];
            if ($second_rent != $order['last_rent']) {
                $order['last_num'] = 1;
            }
            $order['remaining_every_moth'] = $second_rent;
            $order['remaining_num'] = $order['month_total'] - $order['first_num'] - $order['last_num'];
        }

        $order_goods_data = $order->order_goods;
        $order['lease_price'] = $order->order_goods['lease_price'];
        $order['convey_type'] = '寄出' . GoodsService::GOODS_SEND_CONVEY_TYPE_NAME_LIST[$order_goods_data['convey_type1']] . ' | 退货' . GoodsService::GOODS_RETURN_CONVEY_TYPE_NAME_LIST[$order_goods_data['convey_type2']];

        $order['create_time'] = date('Y-m-d H:i:s', $order['create_time']);

        $order['rights_auth_no'] = $order->rights_auth_no;

        if ($order->authentic_log && $order->authentic_log->status != 1) {
            $flow_id = $order->authentic_log->certify_id;
            if ($flow_id) {
                $res = IdCardService::faceCheck($flow_id);
                if ($flow_id && $res['curlRes']['data']['status'] == 'SUCCESS') {
                    //实名认证通过
                    $update['status'] = AuthenticLog::AUTHENTIC_STATUS_PASS;
                    $log = AuthenticLog::where(['certify_id' => $flow_id])->select('id', 'cert_no', 'cert_name', 'idcard_front', 'idcard_back')->first();
                    $log = obToArray($log);
                    if ($log) {
                        AuthenticLog::where(['id' => $log['id']])->update($update);
                        $order->authentic_log->status = 1;
                    }
                }
            }
        }

//        $order['step'] = 0;
//        if (!$order->authentic_log || $order->authentic_log->status != 1) {
//            $order['step'] = 1;
//            $order['url'] = '/pages/id_verify/face?order_id=' . $order->id;
//        }
//        $order['step_button_text'] = '';

//        if ($order->status != 1) {
//            if ($order->authentic_log) {
//                if ($order->authentic_log->status != 1) {
//                    $order['step'] = 1;
//                    $order['url'] = '/pages/id_verify/face?order_id=' . $order->id;
//                    $order['step_button_text'] = '待提交';
//                } else if (!$order->rights_auth_no) {
//                    // $order->pay_type == 2 &&
//                    $order['step'] = 2;
//                    $order['url'] = '/pages/id_verify/face?order_id=' . $order->id;
//                    $order['step_button_text'] = '待提交';
//                }
//            }else{
//                $order['step'] = 1;
//                $order['url'] = '/pages/id_verify/face?order_id=' . $order->id;
//                $order['step_button_text'] = '待提交';
//            }
//        }

        if (!$user['idcard_front'] || !$user['idcard_back']) {
                $order['need_idcard_img'] = 1;
//                $order['step'] = 1;
//                $order['url'] = '/pages/id_verify/face?order_id=' . $order->id;
//                $order['step_button_text'] = '待提交';
        }else {
            $order['need_idcard_img'] = 0;
        }



        $order['status_desc'] = '';
        $order['status_msg'] = '';

        $order['step_text'] = '';
        if ($order->status == 1) {
            $order['status_desc'] = '订单关闭';
            $order['status_msg'] = '您的订单已取消，如有支付金额将在3个工作日内原路退回';
        }
        if ($order->status == 2 ) {
            $order['status_desc'] = '待提交';
            $order['status_msg'] = '您的订单还未人脸实名，赶紧处理吧~';
        }
        if ($order->status == 3 ) {
            $order['status_desc'] = '待支付';
            $order['status_msg'] = '您的订单已审核通过，请签约合同和开通蚂蚁链，赶紧处理吧~';
        }
        if ($order->status == 10) {
            $order['status_desc'] = '待发货';
            $order['status_msg'] = '您的订单审核已完成，等待商家处理，请保持手机畅通，耐心等待';
            $order['lease'] = 1;
            $order['step_button_text'] = '申请退款';
        }
        if ($order->status == 20) {
            $order['status_desc'] = '已发货';
            $order['status_msg'] = '您的商品已发出，签收请注意查验货哦，愿我们给您的生活带来更美好的体验~';
            $order['lease'] = 1;
            $order['url'] = '/pagesA/pages/applyRefund/applyRefund?order_id=' . $order->id;
        }
        if ($order->status == 4) {
            $order['status_desc'] = '审核中';
            $order['status_msg'] = '请耐心等待，审核通过后将在48小时内为您发货';
        }


        $result = [
            "message" => '任何中介名义回收都是骗子！同时建议您收藏小程序',
            'order' => $order,
            "order_lease" => $order_lease
        ];

        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $result);
    }

    public function makeOrder(Request $request)
    {

        $data = $request->all();
        $miniId = AlipayMiniAppService::getInstance()->getMiniId();
        $user = $this->member;
        $data['status'] = OrderService::ORDER_STATUS_NOT_PAY;

        $res = $this->DoOrder($miniId, $data, $user);

        if ($res['status'] == CommonService::HTTP_CODE_SUCCESS) {
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '订单创建成功', $res['data']);
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, $res['msg']);
        }
    }

    public function confirmOrder(Request $request)
    {
        $goods_id = $request->input('goods_id');
        $sku_meal_id = $request->input('sku_meal_id');
        $num = 1;

        if (!$goods_id) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数错误');
        }
        if (!$sku_meal_id) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数错误');
        }

        $goods = Goods::where('id', $goods_id)
            ->where('status', 1)
            ->first();


        $sku_meal_info = GoodsRentSkuMeal::where('id', $sku_meal_id)
            ->with('goods_rent_meal_value.meal')
            ->with('goods_rent_sku')
            ->first();

        if (empty($goods) || $goods->status != 1) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '商品不存在或已下架');
        }

        if (empty($sku_meal_info) || empty($sku_meal_info->goods_rent_sku) || $sku_meal_info->goods_rent_sku->goods_id != $goods->id) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '商品规格不存在或已下架');
        }


        $lease_set = 2;
        $order_goods_data = [];
        $order_goods_data['goods_id'] = intval($goods_id);
        $order_goods_data['goods_title'] = $goods['title'];
        $order_goods_data['imgurl'] = $goods['imgurl'];
        if ($goods['convey_type'] == 1) {
            $order_goods_data['convey_type1'] = 1;
            $order_goods_data['convey_type2'] = 2;
        } else if ($goods['convey_type'] == 2) {
            $order_goods_data['convey_type1'] = 2;
            $order_goods_data['convey_type2'] = 2;
        }


        $meal_array = [];
        foreach ($sku_meal_info['goods_rent_sku']['goods_props'] as $item) {
            $meal_array[] = $item['value']['name'];
        }
        $meal = $sku_meal_info['goods_rent_meal_value']['meal'];
        $meal_array[] = $meal['meal_name'];


        $start_time = time();
        //$lease_time = $sku_meal_info['goods_rent_meal_value']['meal_value'];

        $lease_price = $sku_meal_info['price'];

        $buyout_price = $sku_meal_info['goods_rent_sku']['buyout_price'];
        $end_time = time() + 86400 * $sku_meal_info['goods_rent_meal_value']['meal_value'];
        $order_goods_data['lease_set'] = $lease_set; //天
        $order_goods_data['lease_time'] = $sku_meal_info['goods_rent_meal_value']['meal_value'];


        $order_goods_data['lease_price'] = $lease_price; //商品套餐租金

        $order_goods_data['setmeal_id'] = $sku_meal_info['id'];
        $order_goods_data['setmeal_title'] = implode(' ', $meal_array);
        $order_goods_data['setmeal_price'] = $buyout_price; // 商品套餐买断价格
        $order_goods_data['is_buy_out'] = 2;
        if ($order_goods_data['setmeal_price'] > 0) {
            $order_goods_data['is_buy_out'] = 1;
        }

        $order_goods_data['website_price'] = $sku_meal_info['line_price']; //官方价格
        $order_goods_data['num'] = 1;

        $order = [];
        $order['biz_type'] = $goods['business_type']; // 业务类型 1=租赁 2=分期 3=零售
        $order['lease_price'] = $lease_price;
        $order['buyout_price'] = $buyout_price;


        $order['begin_time'] = date("Y-m-d", $start_time);
        $order['end_time'] = date("Y-m-d", $end_time);


        $calData = (new OrderGoods())->CalRent($goods, $sku_meal_info);

        $order = array_merge($order, $calData);


        $order['convey_type'] = '寄出' . GoodsService::GOODS_SEND_CONVEY_TYPE_NAME_LIST[$order_goods_data['convey_type1']] . ' | 退货' . GoodsService::GOODS_RETURN_CONVEY_TYPE_NAME_LIST[$order_goods_data['convey_type2']];

        $order['total_rent_buyout_price'] =bcadd($order['total_rent'],$order['buyout_price'],2); //租金+买断价


        $result = [
            'order' => $order,
            "order_goods_data" => $order_goods_data,
            "message" => '任何中介名义回收都是骗子！同时建议您收藏小程序',
            "goods_id" => $goods_id,
            "num" => $num,
            "goods" => $goods,
        ];
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $result);

    }


    function ReturnMsg($code, $msg = '', $data = [])
    {
        $arr = array('status' => $code, 'msg' => $msg);
        return $arr;
    }

    public function DoOrder($miniId, $request, $user)
    {
        $realname = $request['realname'] ?? '';
        $mobile = $request['mobile'] ?? '';
        $address = $request['address'] ?? '';
        $goods_id = $request['goods_id'] ?? '';
        $sku_meal_id = $request['sku_meal_id'] ?? '';
        $selected_service = $request['selected_service'] ?? '';
        $scene =$request['scene'] ?? '';

        $location=$request['location']??'';
        if(!$location){
            $location=getCityByIP();
        }

        $num = 1;
        if (!$goods_id) {
            return $this->ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数错误');
        }
        if (!$sku_meal_id) {
            return $this->ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数错误');
        }
        if (!$realname || !$mobile || !$address) {
            return $this->ReturnMsg(CommonService::HTTP_CODE_FAIL, '地址不存在');
        }
        if (empty($user['mobile'])) {
            return $this->ReturnMsg(CommonService::HTTP_CODE_FAIL, '未授权手机号码');
        }
        if(!empty($request['prov'])&&in_array(mb_substr($request['prov'],0,2),['内蒙','西藏','新疆'])){
            return $this->ReturnMsg(CommonService::HTTP_CODE_FAIL, '校验不通过');
        }

        if(Redis::get('user_order_limit_crate_order_black_'.$user['id'])){
            return $this->ReturnMsg(CommonService::HTTP_CODE_FAIL, '操作过于频繁的，30天后再来尝试');
        }

         if(Redis::get('user_legal_black'.$user['id'])||Redis::get('user_limit_crate_order_black_'.$user['id'])){
             return $this->ReturnMsg(CommonService::HTTP_CODE_FAIL, '操作过于频繁，30天后再来尝试');
         }


        $risk=OrderDlzwRisk::query()->where('cert_no', $user['cert_no'])->where('risk_level', 'F')
            ->where('create_time','>',strtotime('- 30 days'))->exists();
        if ($risk) {
            return $this->ReturnMsg(CommonService::HTTP_CODE_FAIL, '校验不通过，请30天后重试');
        }
        $orderExists=Order::query()->whereIn('status',[10,20,30,38,39])->where('uid', $user['id'])->exists();

        if($orderExists){
            return $this->ReturnMsg(CommonService::HTTP_CODE_FAIL, '您已有履约订单，请勿重复下单');
        }


        if (!$user['cert_no'] || !$user['cert_name']) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '未实名认证', 'data' => []];
        }
        $goods = Goods::where('id', $goods_id)
            ->with('goods_rent_sku.goods_rent_sku_meal.goods_rent_meal_value')
            ->with(['goods_class' => function ($query) {
                $query->select('id', 'name');
            }])
            ->with(['goods_type' => function ($query) {
                $query->select('id', 'name');
            }])
            ->with(['brand' => function ($query) {
                $query->select('id', 'name');
            }])
            ->with(['shop' => function ($query) {
                $query->select("id", "member_id", "shopname");
            }])
            ->first();

        $userOrderCount=Order::query()->where('uid', $user['id'])->whereBetween('create_time',[time()-86400,time()])->count();

        if($userOrderCount>=5){
            Redis::setex('user_limit_crate_order_black_'.$user['id'],86400*7,1);
            return $this->ReturnMsg(CommonService::HTTP_CODE_FAIL, '操作过于频繁，７天后再来尝试');
        }
        if($userOrderCount>=3){
            $count=Order::query()->from('sp_order_2 as o')
                ->leftJoin('sp_order_goods_2 as og', 'og.order_id', '=', 'o.id')
                ->leftJoin('sp_goods_2 as g', 'g.id', '=', 'og.goods_id')
                ->whereIn('g.category_id',['11','15','10'])
                ->where('o.uid', $user['id'])
                ->whereBetween('o.create_time',[time()-86400,time()])
                ->count();
            if($count>=3){
                Redis::setex('user_limit_crate_order_black_'.$user['id'],86400*7,1);
                return $this->ReturnMsg(CommonService::HTTP_CODE_FAIL, '操作过于频繁，７天后再来尝试');
            }
        }




        $sku_meal_info = GoodsRentSkuMeal::where('id', $sku_meal_id)
            ->with('goods_rent_meal_value.meal')
            ->with('goods_rent_sku')
            ->first();

        if (empty($goods) || $goods->status != 1) {
            return $this->ReturnMsg(CommonService::HTTP_CODE_FAIL, '商品不存在或已下架');
        }

        if (empty($sku_meal_info) || empty($sku_meal_info->goods_rent_sku) || $sku_meal_info->goods_rent_sku->goods_id != $goods->id) {
            return $this->ReturnMsg(CommonService::HTTP_CODE_FAIL, '商品规格不存在或已下架');
        }


        if ($sku_meal_info->goods_rent_sku->off_sale != 0) {
            return $this->ReturnMsg(CommonService::HTTP_CODE_FAIL, '商品禁售');
        }

        if($goods['business_type']==GoodsBusinessEnum::LEASE()->getKey()){
            $lease_set = 1;  //月
            $timeUnit='month';
        }else{
            $lease_set = 2;  //季
            $timeUnit='days';
        }

        // 订单商品
        $order_goods_data = [];
        $order_goods_data['goods_id'] = intval($goods_id);
        $order_goods_data['goods_title'] = $goods['title'];
        $order_goods_data['goods_name'] = $goods['goods_name'];
        $order_goods_data['imgurl'] = $goods['imgurl'];
        if ($goods['convey_type'] == 1) {
            $order_goods_data['convey_type1'] = 1;
            $order_goods_data['convey_type2'] = 2;
        } else if ($goods['convey_type'] == 2) {
            $order_goods_data['convey_type1'] = 2;
            $order_goods_data['convey_type2'] = 2;
        }


        $meal_array = [];
        foreach ($sku_meal_info['goods_rent_sku']['goods_props'] as $item) {
            $meal_array[] = $item['value']['name'];
        }
        $meal = $sku_meal_info['goods_rent_meal_value']['meal'];
        $meal_array[] = $meal['meal_name'];


        $start_time = time();
        $lease_time = $sku_meal_info['goods_rent_meal_value']['meal_value'];

        $lease_price = $sku_meal_info['price'];

        $buyout_price = $sku_meal_info['goods_rent_sku']['buyout_price'];

        $end_time = strtotime('+' . $lease_time . ' ' . $timeUnit, $start_time);

        $order_goods_data['lease_set'] = $lease_set; //天
        $order_goods_data['lease_time'] = $sku_meal_info['goods_rent_meal_value']['meal_value'];


        $order_goods_data['lease_price'] = $lease_price; //商品套餐租金

        $order_goods_data['setmeal_id'] = $sku_meal_info['meal_value_id'];
        $order_goods_data['sku_meal_id'] = $sku_meal_info['id'];
        $order_goods_data['setmeal_title'] = implode(' ', $meal_array);
        $order_goods_data['setmeal_price'] = $buyout_price; // 商品套餐买断价格
        $order_goods_data['is_buy_out'] = 2;
        $order_goods_data['pact_type'] = 2;

        if ($order_goods_data['setmeal_price'] > 0) {
            $order_goods_data['is_buy_out'] = 1;
            $order_goods_data['pact_type'] = 1;
        }

        $order_goods_data['website_price'] = $sku_meal_info['line_price']; //官方价格


        $order_goods_data['start_date'] = 0;
        $order_goods_data['create_time'] = time();
        //$order_goods_data['num'] = 1;

        // 订单
        $order = [];

        $order['biz_type'] = $goods['business_type'];
        $calData = (new OrderGoods())->CalRent($goods, $sku_meal_info);
        if ($calData['first_rent'] <= 0) {
            return $this->ReturnMsg(CommonService::HTTP_CODE_FAIL, '优惠设置错误');
        }


        $order['location'] = $location;
        $order['scene'] = $scene;
        $order['discount_type'] = $calData['discount_type'];
        $order['discount_amount'] = $calData['discount_amount'];
        $order['discount_name'] = $calData['discount_name'];

        $order['rent_total'] = $calData['rent_total'];
        $order_goods_data['setmeal_foregift'] = bcadd( $order['rent_total'], $buyout_price, 2); //官方价格

        $order['foregift'] = $order['rent_total'];
        $order['month_total'] = $calData['month_total'];

        $order['remark'] = !empty($request['remark']) ? $request['remark'] : '';
        $order['prov'] = !empty($request['prov']) ? $request['prov'] : '';
        $order['city'] = !empty($request['city']) ? $request['city'] : '';
        $order['area'] = !empty($request['area']) ? $request['area'] : '';
        $order_from = !empty($request['order_from']) ? $request['order_from'] : ''; // 订单来源
        $order['order_from'] = $order_from;

        $order_sn = createNo();
        $order['amount'] = $num; // 商品数量
        $order['seller_id'] = $goods['member_id'];
        $order['mini_id'] = $miniId;

        $order['uid'] = $user['id'];
        $order['trade_no'] = $order_sn;
        $order['realname'] = $realname;
        $order['mobile'] = $mobile;
        $order['address'] = preg_replace('/\s*/', '', stripslashes(strval($address)));

        $order['create_time'] = time();
        $order['update_time'] = time();
        $order['pay_type'] = 1; // 支付类型;  1智能合同代扣；2预授权； 3花呗 4 全额买断'
        $order['contract_type'] = 2;
        $order['prepayment_total'] = 1;
        $order['sign_num'] = 3;
        $order['relation_id'] = 0;
        $order['phone_brand'] = !empty($request['phone_brand']) ? $request['phone_brand'] : '';
        //$order['pay_type'] = $goods['pay_type'];
        $order['payer_user_id'] = $user['user_id'];
        $order['status'] = OrderService::ORDER_STATUS_SIGN_NOCHECK; //待认证

        $order['reduced_price'] = $buyout_price; // 买断价格


        $order['begin_time'] = date("Y-m-d H:i:s", $start_time);
        $order['end_time'] = date("Y-m-d H:i:s", $end_time);



        if($selected_service){
            $order['is_insurance_choose'] = 100;
            $order['is_insurance_choose_custom'] = $goods['service_price'];
        }


        $trade_no = $order['trade_no'];
        $order_id = 0;
        // ===================事务开始
        DB::beginTransaction();
        try {
            // 生成订单
            $order_id = DB::table('sp_order_2')->insertGetId($order);
            $order_goods_data['order_id'] = $order_id;
            // 生成订单商品
            DB::table('sp_order_goods_2')->insert($order_goods_data);
            $order_lease = $this->getOrderLease($order_id, $calData, $start_time, $end_time);
            // 批量生成账单
            DB::table('sp_order_lease_2')->insert($order_lease);

        } catch (\Exception $e) {
            DB::rollBack();
            return ["status" => CommonService::HTTP_CODE_FAIL, "msg" => '下单失败' . $e->getMessage()];
        }
        DB::commit();
        // ===================事务结束

        // 获取账单列表
        // 批量插入
        ProcessPodcast::dispatch($order_id);

        SendChangeOrderMessage::dispatch($order_id,AlipayMessageService::KX_SHOPPING);
        SendChangeOrderMessage::dispatch($order_id,AlipayMessageService::CONSUMER)->delay(10);
        SendSmsMessageJob::dispatch(SmsTempEnum::ORDER_PLACED,$order_id);

        $result = [
            "status" => 200,
            "msg" => "ok",
            'data' => [
                "order_id" => $order_id,
                "trade_no" => $trade_no,
            ],
        ];
        return $result;
    }


    public function getOrderLease($order_id, $calData, $start_time, $end_time)
    {

        $data = [];
        $now = time();
        for ($i = 0; $i < $calData['month_total']; $i++) {
            $s_time = date('Y-m-d', strtotime('+' . $i . 'month', ($start_time)));
            $e_time = date('Y-m-d', strtotime(date('Y-m-d', strtotime('+' . ($i + 1) . 'month', ($start_time)))) - 24 * 60 * 60);

            $rent = 0;
            if ($i == 0) {
                $rent = $calData['first_rent'];
            } else if ($calData['month_total'] == $i + 1) {
                $rent = $calData['last_rent'];
                $e_time = date("Y-m-d", $end_time);
            } else {
                $rent = $calData['every_month'];
            }

            $data[] = [
                "begin_time" => strtotime($s_time),
                "end_time" => strtotime($e_time . " 23:59:59"),
                "order_id" => $order_id,
                "which_period" => $i + 1,
                'paid_rent' => 0,
                "create_time" => $now,
                "rent" => $rent
            ];
        }
        return $data;
    }



}
